<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users_model extends CI_Model {
    public $table = 'mltv_users';
    private $data = array();

    public function __construct() {
        parent::__construct();
    }
	
	public function setData($data){
		$result = array();
		foreach($data as $key => $row){
			if($this->db->field_exists($key, $this->table)){
				$result[$key] = $row;
			}
		}
		$this->data = $result;
	} 
	public function getData(){
		return $this->data;
	}
    public function get($id) {
        $result =  $this->db->select()->from($this->table)->where('id',$id)->get()->row_array();
        $obj = FALSE;
        if ($result) {
            $obj = new self();
            $obj->setData($result);
        }
        return $obj;
    }
    public function getAll($filter = array()) {
		if (isset ( $filter ['field'] ) and strlen ( $filter ['field'] )) {
				$this->db->select( $filter ['field'] );
		} else {
				$this->db->select();
		}
		$this->db->from ( $this->table );
		foreach($filter as $key => $row){
			if(strpos($key, '_eq')){
				$this->db->where(str_replace('_eq', ' ', $key ), $row);
			}else if(strpos($key, '_lk')){
				$this->db->like(str_replace('_lk', ' ', $key ), $row);
			}
		}
		$order = 'id';
		$this->db->order_by ( $order );
		$query = $this->db->get ();
		return $query;
    }

	public function getByParams($limit, $dir = 'ASC', $sort = 'id', $start, $filter = array()) {
		$this->db->select()->order_by ( $sort, $dir );
		foreach($filter as $key => $row){
			if(strpos($key, '_eq')){
				$this->db->where(str_replace('_eq', ' ', $key ), $row);
			}else if(strpos($key, '_lk')){
				$this->db->like(str_replace('_lk', ' ', $key ), $row);
			}else if(strpos($key, '_not')){
				$this->db->where(str_replace('_not', ' ', $key )."!=", $row);
			}
		}
		$query = $this->db->get ( $this->table, $limit, $limit * $start - $limit );
		return $query;
	}

    public function save(){

		if(!isset($this->data['id']) || empty($this->data['id'])){
			$this->db->insert($this->table,$this->data);
			$this->data['id'] = $this->db->insert_id();
			return $this->data['id'];
		}else{
			$this->db->where('id',$this->data['id']);
			$this->db->update($this->table, $this->data);
			return $this->data['id'];
		}
    }

	public function delete(){
		if(!isset($this->data['id']) || empty($this->data['id'])){
			return false;
		}
		$this->db->where('id',$this->data['id']);
		$this->db->delete($this->table);
		return ($this->db->affected_rows() > 0) ? TRUE : FALSE;
	}

}